<!DOCTYPE html>
<html>
<head>
    <title>Parameter Validator Admin</title>
    <meta charset="UTF-8">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f8f9fa;
        }

        h1, h2 {
            color: #2c3e50;
        }

        .container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #495057;
        }

        input, select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            box-sizing: border-box;
        }

        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        button:hover {
            background-color: #0069d9;
        }

        .rule-item {
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 10px;
            background-color: #f8f9fa;
        }

        .rule-item h3 {
            margin-top: 0;
            color: #212529;
        }

        .rule-item p {
            margin: 5px 0;
            color: #6c757d;
        }

        .delete-btn {
            background-color: #dc3545;
        }

        .delete-btn:hover {
            background-color: #c82333;
        }

        .error {
            color: #dc3545;
            margin-top: 5px;
        }
    </style>
</head>
<body>
<h1>Parameter Validation Rules</h1>

<div class="container">
    <h2>Application Configuration</h2>
    <div class="form-group">
        <label for="appId">Application ID:</label>
        <input type="text" id="appId" value="default-app">
    </div>
    <button onclick="loadRules()">Load Rules</button>
</div>

<div class="container">
    <h2>Add New Rule</h2>
    <div class="form-group">
        <label for="paramPath">Parameter Path (e.g., user.address.city):</label>
        <input type="text" id="paramPath" placeholder="user.address.city">
    </div>

    <div class="form-group">
        <label for="ruleType">Rule Type:</label>
        <select id="ruleType">
            <option value="NOT_NULL">Not Null</option>
            <option value="NOT_EMPTY">Not Empty</option>
            <option value="MIN_LENGTH">Min Length</option>
            <option value="MAX_LENGTH">Max Length</option>
            <option value="RANGE">Numeric Range</option>
            <option value="REGEX">Regex Pattern</option>
            <option value="EMAIL">Email Format</option>
        </select>
    </div>

    <div class="form-group" id="ruleConfigContainer">
        <label for="ruleConfig">Rule Configuration:</label>
        <input type="text" id="ruleConfig" placeholder="Depends on rule type">
        <div class="error" id="configError"></div>
    </div>

    <div class="form-group">
        <label for="errorMsg">Error Message:</label>
        <input type="text" id="errorMsg" placeholder="Validation failed message">
    </div>

    <button onclick="addRule()">Add Rule</button>
</div>

<div class="container">
    <h2>Current Rules</h2>
    <div id="rulesContainer">
        <p>No rules found. Add a rule or load from an application.</p>
    </div>
</div>

<script>
    // DOM Elements
    const appIdInput = document.getElementById('appId');
    const ruleTypeSelect = document.getElementById('ruleType');
    const ruleConfigInput = document.getElementById('ruleConfig');
    const configError = document.getElementById('configError');
    const rulesContainer = document.getElementById('rulesContainer');

    // Initialize with default app ID
    let currentAppId = appIdInput.value;

    // Configure rule type changes
    ruleTypeSelect.addEventListener('change', updateRuleConfig);

    function updateRuleConfig() {
        const ruleType = ruleTypeSelect.value;
        configError.textContent = '';

        switch(ruleType) {
            case 'MIN_LENGTH':
            case 'MAX_LENGTH':
                ruleConfigInput.placeholder = 'e.g., 5';
                break;
            case 'RANGE':
                ruleConfigInput.placeholder = '{"min": 0, "max": 100}';
                break;
            case 'REGEX':
                ruleConfigInput.placeholder = 'Regular expression pattern';
                break;
            default:
                ruleConfigInput.placeholder = 'No configuration needed';
        }
    }

    // Load rules for current application
    async function loadRules() {
        const appId = appIdInput.value;
        currentAppId = appId;

        try {
            const response = await fetch(`/validator-admin/rules?appId=${appId}`);
            if (!response.ok) {
                throw new Error(`Failed to load rules: ${response.status}`);
            }

            const rules = await response.json();
            displayRules(rules);
        } catch (error) {
            showError(`Error loading rules: ${error.message}`);
        }
    }

    // Display rules in the UI
    function displayRules(rules) {
        if (rules.length === 0) {
            rulesContainer.innerHTML = '<p>No rules found for this application.</p>';
            return;
        }

        rulesContainer.innerHTML = '';

        rules.forEach(rule => {
            const ruleElement = document.createElement('div');
            ruleElement.className = 'rule-item';

            let configText = '';
            if (rule.ruleConfig) {
                if (rule.ruleType === 'RANGE') {
                    try {
                        const config = JSON.parse(rule.ruleConfig);
                        configText = `Min: ${config.min}, Max: ${config.max}`;
                    } catch {
                        configText = rule.ruleConfig;
                    }
                } else {
                    configText = rule.ruleConfig;
                }
            }

            ruleElement.innerHTML = `
                    <h3>${rule.paramPath}</h3>
                    <p><strong>Rule Type:</strong> ${rule.ruleType}</p>
                    ${configText ? `<p><strong>Config:</strong> ${configText}</p>` : ''}
                    <p><strong>Error Message:</strong> ${rule.errorMsg}</p>
                    <button class="delete-btn" onclick="deleteRule(${rule.id})">Delete Rule</button>
                `;

            rulesContainer.appendChild(ruleElement);
        });
    }

    // Add a new rule
    async function addRule() {
        const rule = {
            paramPath: document.getElementById('paramPath').value,
            paramType: 'String', // Simplified for this demo
            ruleType: ruleTypeSelect.value,
            ruleConfig: document.getElementById('ruleConfig').value,
            errorMsg: document.getElementById('errorMsg').value,
            appId: currentAppId
        };

        // Validate configuration
        if (!validateRuleConfig(rule)) {
            return;
        }

        try {
            const response = await fetch('/validator-admin/rules', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(rule)
            });

            if (!response.ok) {
                throw new Error(`Failed to add rule: ${response.status}`);
            }

            // Clear form
            document.getElementById('paramPath').value = '';
            document.getElementById('ruleConfig').value = '';
            document.getElementById('errorMsg').value = '';

            // Reload rules
            loadRules();
        } catch (error) {
            showError(`Error adding rule: ${error.message}`);
        }
    }

    // Validate rule configuration
    function validateRuleConfig(rule) {
        configError.textContent = '';

        try {
            switch(rule.ruleType) {
                case 'MIN_LENGTH':
                case 'MAX_LENGTH':
                    if (!rule.ruleConfig || isNaN(parseInt(rule.ruleConfig))) {
                        configError.textContent = 'Please enter a valid number';
                        return false;
                    }
                    break;
                case 'RANGE':
                    if (!rule.ruleConfig) {
                        configError.textContent = 'Please enter a JSON range config';
                        return false;
                    }

                    try {
                        const config = JSON.parse(rule.ruleConfig);
                        if (config.min === undefined || config.max === undefined) {
                            configError.textContent = 'Range config must have min and max properties';
                            return false;
                        }
                    } catch {
                        configError.textContent = 'Invalid JSON format';
                        return false;
                    }
                    break;
                case 'REGEX':
                    if (!rule.ruleConfig) {
                        configError.textContent = 'Please enter a regex pattern';
                        return false;
                    }

                    try {
                        new RegExp(rule.ruleConfig);
                    } catch {
                        configError.textContent = 'Invalid regular expression';
                        return false;
                    }
                    break;
            }
            return true;
        } catch (error) {
            configError.textContent = error.message;
            return false;
        }
    }

    // Delete a rule
    async function deleteRule(ruleId) {
        if (!confirm('Are you sure you want to delete this rule?')) {
            return;
        }

        try {
            const response = await fetch(`/validator-admin/rules/${ruleId}`, {
                method: 'DELETE'
            });

            if (!response.ok) {
                throw new Error(`Failed to delete rule: ${response.status}`);
            }

            // Reload rules
            loadRules();
        } catch (error) {
            showError(`Error deleting rule: ${error.message}`);
        }
    }

    // Show error message
    function showError(message) {
        alert(`Error: ${message}`);
    }

    // Initialize on load
    window.onload = function() {
        updateRuleConfig();
        loadRules();
    };
</script>
</body>
</html>